import { use } from 'echarts';
import React, { useState, useEffect, useRef } from 'react';
import { JSONEditor } from 'vanilla-jsoneditor/standalone.js';

interface JSONEditorProps {
  option: {};
  onDataChange: (data: any) => void;
}
interface TargetType {
  x: String,
  y: String,
  color?: String,
  type?: String,
  data: { x: string; y: number; }[]
}

function isTargetType(obj: unknown): obj is TargetType {
  return typeof obj === 'object' && obj !== null && 'x' in obj && 'y' in obj && 'data' in obj && Array.isArray(obj.data) && obj.data.every(item => typeof item === 'object' && item !== null);
}

interface updatedContentType {
  text: String
}

function isUpdatedContentType(obj: unknown): obj is updatedContentType {
  return typeof obj === 'object' && obj !== null && 'text' in obj && typeof obj.text === 'string';
}

const JSONEditorComponent: React.FC<JSONEditorProps> = ({ option, onDataChange }) => {
  let json: TargetType = {
    x: "x",
    y: "y",
    data: [
      { x: 'Sports', y: 275 },
      { x: 'Strategy', y: 115 },
      { x: 'Action', y: 120 },
      { x: 'Shooter', y: 350 },
      { x: 'Other', y: 150 },
    ]
  }

  if (isTargetType(option)) {
    json = option;
  }

  console.log(isTargetType(option), "option");
  let content =
  {
    json: json
  }
  const [data, setData] = useState(content);
  const editorRef = useRef(null);

  const handleDataChange = (dataIn: any) => {
    setData({
      ...dataIn
    });
    onDataChange(dataIn);
  };

  useEffect(() => {
    if (editorRef.current) {
      const editor = new JSONEditor(
        {
          target: editorRef.current,
          props: {
            content: content,
            onChange: (updatedContent, previousContent, { contentErrors, patchResult }) => {
              // content is an object { json: unknown } | { text: string }
              console.log('onChange', { updatedContent, previousContent, contentErrors, patchResult })
              if (patchResult && isTargetType(patchResult.json)) {
                handleDataChange({
                  ...content,
                  json: patchResult.json
                })
                console.log(data, "updatedContent")
              } else {
                if (updatedContent && isUpdatedContentType(updatedContent)) {
                  console.log(updatedContent.text, "text");
                  handleDataChange({
                    ...content,
                    json: JSON.parse(updatedContent.text)
                  })
                }
              }
            }
          }
        }
      );
      // 清理函数，防止内存泄漏
      return () => {
        editor.destroy();
      };
    }
  }, []); // 空数组意味着只在组件挂载时运行一次

  return (
    <div>
      <div ref={editorRef} />
      {/* 其他组件 */}
    </div>
  );
}

export default JSONEditorComponent
